//
//  ArchiverManager.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/5.
//

import UIKit

class ArchiverManager: NSObject {
    static let shared = ArchiverManager()
    private override init() {
        super.init()
    }
    // 获取路径
    private func getFilePath(path : String) -> String {
        let file = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        return file.asNSString.appendingPathComponent(path)
    }

    //MARK:- 归档数据
    func setData(data : Any, forKey : String, path : String) -> Bool {
        do {
            let archiver = try NSKeyedArchiver.archivedData(withRootObject: data, requiringSecureCoding: true)
            do {
                try archiver.write(to: URL(fileURLWithPath: getFilePath(path: path)))
                return true
            } catch {
                print("data写入本地失败: \(error)")
                return false
            }
        } catch {
            print("模型转data失败: \(error)")
            return false
        }
    }

    //MARK:- 解档数据
    func getData(forKey : String, forPath : String) -> Any? {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: getFilePath(path: forPath)))
            let model : Any? = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
            return model
        } catch {
//            print("获取data数据失败: \(error)")
            return nil
        }
    }

    func removeData(forPath : String) {
        let fm = FileManager.default
        do {
            try fm.removeItem(atPath: getFilePath(path: forPath))
        } catch {
            print("删除data数据失败: \(error)")
        }
    }
}
